package com.rosense.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import com.rosense.client.rpc.RPCBean;
import com.rosense.client.rpc.RPCMemBean;

/**
 * 0 表示内存
 * 采集内存使用率 
 * @author 李岩飞
 * @email eliyanfei@126.com	
 * 2018年1月23日 下午1:51:07
 *
 */
public class MemUsage extends ResourceUsage {
	private static MemUsage INSTANCE = new MemUsage();

	private MemUsage() {
	}

	public static MemUsage getInstance() {
		return INSTANCE;
	}

	/** 
	 * Purpose:采集内存使用率 
	 * @param args 
	 * @return float,内存使用率,小于1 
	 */
	@Override
	public RPCBean scan() {
		Process pro = null;
		RPCMemBean rpc = new RPCMemBean();
		Runtime r = Runtime.getRuntime();
		try {
			String command = "cat /proc/meminfo";
			pro = r.exec(command);
			BufferedReader in = new BufferedReader(new InputStreamReader(pro.getInputStream()));
			String line = null;
			int count = 0;
			long totalMem = 0, freeMem = 0, cached = 0;//kb
			while ((line = in.readLine()) != null) {
				String[] memInfo = line.split("\\s+");
				if (memInfo[0].startsWith("MemTotal")) {
					totalMem = Long.parseLong(memInfo[1]);
					count++;
				}
				if (memInfo[0].startsWith("MemFree")) {
					freeMem = Long.parseLong(memInfo[1]);
					count++;
				}
				if (memInfo[0].startsWith("Cached")) {
					cached = Long.parseLong(memInfo[1]);
					count++;
				}

				if (count >= 3) {
					break;
				}
			}
			rpc.cached = cached;
			rpc.total = totalMem;
			rpc.used = totalMem - freeMem;
			in.close();
			pro.destroy();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return rpc;
	}

}